import { ResponseInterceptor } from './../../../interceptor/response/response.interceptor';
import { AccessService } from './../../../service/access/access.service';
import { Controller, Get, Post, Patch, Delete, Body, UseInterceptors, Request } from '@nestjs/common';
import config from '../../../config/config';
import * as mongoose from 'mongoose';

@Controller(`${config.adminPath}/access`)
@UseInterceptors(ResponseInterceptor)
export class AccessController {
    constructor(private readonly accessService: AccessService) {}
    @Get()
    async find() {
        // return await this.accessService.find();
        return await this.accessService.getModel().aggregate([
            {
                $lookup: {
                    from: 'access',
                    localField: '_id',
                    foreignField: 'module_id',
                    as: 'children',
                    pipeline: [
                        {
                            $sort: {
                                type: 1,
                                sort: 1,
                            },
                        },
                    ],
                },
            },
            {
                $match: {
                    module_id: '0',
                },
            },
        ]);
    }
    @Post()
    async create(@Body() body) {
        const { module_id } = body;
        if (module_id && module_id !== '0') {
            body.module_id = new mongoose.Types.ObjectId(module_id);
        }
        return await this.accessService.create(body);
    }
    @Patch()
    async update(@Body() body) {
        const { module_id } = body;
        if (module_id && module_id !== '0') {
            body.module_id = new mongoose.Types.ObjectId(module_id);
        }
        return await this.accessService.update(body);
    }
    @Delete()
    async delete(@Body() body) {
        return await this.accessService.delete(body);
    }
    @Get('/menu')
    async getMenu(@Request() req) {
        return await this.accessService.getMenu(req);
    }
}
